package com.xuecheng.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.AuthInfoHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

/**
 * @author Sober_wxy
 * @date 2022/7/16 17:38
 * 自定义拦截器
 */
public class AuthInfoInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                // 获取请求头中的 payload
                String payload = request.getHeader("payload");
                if (StringUtils.isEmpty(payload)) {
                        return true;
                }
                // 转化编码
                String json = URLDecoder.decode(payload, "Utf-8");
                // 转化成AuthInfo对象
                AuthInfo authInfo = JSON.parseObject(json, AuthInfo.class);
                // 存入ThreadLocal 线程对象（只作用于 微服务器的线程 拦截器启）
                AuthInfoHolder.setAuthInfo(authInfo);
                return HandlerInterceptor.super.preHandle(request, response, handler);
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

                HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        }
}
